import os
import sys

from PyQt5.QtGui import QIcon, QColor
from PyQt5.QtWidgets import QWidget, QGridLayout, QLabel, QApplication, QVBoxLayout

from ClientUi.controls.DeviceStatusList import DeviceStatusList
from ClientUi.controls.LogList import LogList
from ClientUi.controls.PanelsGroupWidget import PanelsGroupWidget
from ClientUi.controls.StatisticsWidget import StatisticsWidget


class MsgPanels(PanelsGroupWidget):

    def __init__(self):
        super().__init__(3)
        self.setMaximumWidth(350)

    def __createStatisticsWidget(self):
        panel = QWidget()
        v = QVBoxLayout()
        self.__statistics = StatisticsWidget()
        self.__statistics.setFixedHeight(155)
        # self.__statistics.setMaximumHeight(180)
        v.addWidget(self.__statistics)
        v.addStretch()
        # v.setSpacing(30)
        v.setContentsMargins(3, 0, 3, 0)
        panel.setLayout(v)
        return panel

    def __createDevsWidget(self):
        self.__tableWidget = DeviceStatusList()
        #self.__tableWidget.setMinimumHeight(100)
        self.__tableWidget.setStatusIcons(self.__devIconConnected, self.__devIconUnconnected)
        return self.__tableWidget

    def __createLogWidget(self):
        self.__listWidget = LogList(self)
        #self.__listWidget.setMinimumHeight(100)
        self.__listWidget.setObjectName("LogListWidget")
        return self.__listWidget

    def _initUi(self):
        super()._initUi()
        currentPath = os.path.abspath(__file__)
        self._clientUiPath = os.path.dirname(currentPath)
        self.__panelIconMin = QIcon(f'{self._clientUiPath}\\images\\min.png')
        self.__panelIconRestore = QIcon(f'{self._clientUiPath}\\images\\max.png')
        self.__panelIconClose = QIcon(f'{self._clientUiPath}\\images\\close.png')
        self.SetIcons(self.__panelIconMin, self.__panelIconRestore, self.__panelIconClose)

        self.__devIconConnected = QIcon(f'{self._clientUiPath}\\images\\iconConnected.png')
        self.__devIconUnconnected = QIcon(f'{self._clientUiPath}\\images\\iconUnconnected.png')
        w = self.__createStatisticsWidget()
        self.SetCustomWidget(0, w)
        self.SetTitle(0, '统计栏')
        #self.SetPanelMinHeight(0, 180)
        w = self.__createDevsWidget()
        self.SetCustomWidget(1, w)
        self.SetTitle(1, '设备栏')
        w = self.__createLogWidget()
        self.SetCustomWidget(2, w)
        self.SetTitle(2, '日志栏')
        # self.SetPanelStretch(0, 1)
        # self.SetPanelStretch(1, 1)
        # self.SetPanelStretch(2, 2)

    def AppendLog(self, msg: str, color: QColor):
        try:
            self.__listWidget.appendLog(msg, color)
        except Exception as e:
            print(sys.exc_info())

    def ClearLog(self):
        try:
            self.__listWidget.clear()
        except Exception as e:
            print(sys.exc_info())

    def SetStatistics(self, stats):
        try:
            self.__statistics.SetStatistics(stats)
        except Exception as e:
            print(sys.exc_info())

    def ClearStatistics(self):
        try:
            self.__statistics.ClearStatistics()
        except Exception as e:
            print(sys.exc_info())

    # 设置设备列表及设备状态
    # 第一个参数为设备名称, 第二个参数为IP或串口号, 第三个参数为连接状态
    # devs = [['camera - 1', '192.168.1.1', True], ['scanner - 1', 'COM1'], ['PLC - 1', '192.168.2.1', False]]
    def SetDevsList(self, devs):
        try:
            num_rows = len(devs)
            self.__tableWidget.clear()
            self.__tableWidget.setRowCount(num_rows)
            for i, row_data in enumerate(devs):
                if len(row_data) >= 3:
                    self.__tableWidget.setRow(i, row_data[0], row_data[1], row_data[2])
                else:
                    self.__tableWidget.setRow(i, row_data[0], row_data[1])
            self.__tableWidget.resizeColumnWidth()
        except Exception as e:
            print(sys.exc_info())

    # 根据IP或者串口号更新设备状态（只更新状态，不修改列表项）
    # devs = [['192.168.1.1', True], ['COM1', True]]
    def updateDevStatus(self, devs):
        try:
            for row_data in devs:
                self.__tableWidget.updateStatus(row_data[0], row_data[1])
        except Exception as e:
            print(sys.exc_info())

    # 清除设备栏
    def ClearDevList(self):
        try:
            self.__tableWidget.clear()
        except Exception as e:
            print(sys.exc_info())



if __name__ == "__main__":
    app = QApplication(sys.argv)
    try:
        current_path = os.path.abspath(__file__)
        path = os.path.dirname(current_path)
        #path = os.path.dirname(path)
        #app.setStyleSheet(open(f'{path}/styleSheet.qss', encoding='utf-8').read())
        window = MsgPanels()
        window.setMinimumWidth(200)
        window.setMinimumHeight(400)
        #window.setFixedSize(300, 500)
        window.SetStatistics(('OK', 987654, 12345, 99.765))
        window.SetDevsList([['camera - 1', '192.168.1.1', True], ['scanner - 1', 'COM1'], ['PLC - 1', '192.168.2.1', False]])
        for i in range(1234):
            window.AppendLog(f'log {i}', QColor('red'))

        window.showNormal()
        sys.exit(app.exec_())

    except Exception as e:
        print(e)
